package com.util_code.base.mvp;

import java.util.Iterator;
import java.util.Map;

import io.reactivex.Completable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

import com.alibaba.fastjson.JSONObject;

public class RxMvpPresenter<V extends MvpView> extends MvpBasePresenter<V> {

    protected CompositeDisposable mCompositeDisposable;
    protected Completable retryCompletable;

    protected void addSubscribe(Disposable subscription) {
        if (mCompositeDisposable == null) {
            mCompositeDisposable = new CompositeDisposable();
        }
        mCompositeDisposable.add(subscription);
    }

    protected void unSubscribe() {
        if (mCompositeDisposable != null) {
            mCompositeDisposable.clear();
        }
    }

    @Override
    public void detachView() {
        super.detachView();
        unSubscribe();
    }

    public void errorRetry() {
        if (retryCompletable != null) {
            addSubscribe(retryCompletable.subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe());

        }
    }

    public void setErrorRetry(final Action action) {
        if (action == null) {
            this.retryCompletable = null;
        } else {
            this.retryCompletable = Completable.fromAction(action);
        }
    }

    protected RequestBody onRequestBody(Map<String, Object> param) {
        JSONObject object = new JSONObject();
        Iterator iter = param.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            String key = (String)entry.getKey();
            Object val = entry.getValue();
            object.put(key, val);
        }
        return onRequestBody(object);
    }

    protected RequestBody onRequestBody(JSONObject object) {
        return RequestBody.create(object.toString(), MediaType.parse("application/json; charset=utf-8"));
    }


}
